package com.ctakit.sdk.app.widget.tab.home;

import android.content.Context;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.LayoutRes;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import java.util.List;

/**
 * Created by andyhome on 16/5/11.
 */
public class HomeTabLayout extends LinearLayout  implements IHomeTabLayout<HomeTabFragment> {

    private AbsTabAdapter mAdapter;

    public HomeTabLayout(Context context) {
        super(context);
        setOrientation(HORIZONTAL);
    }

    public HomeTabLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        setOrientation(HORIZONTAL);
    }

    public HomeTabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setOrientation(HORIZONTAL);
    }

    public static abstract class AbsTabAdapter<DataType extends SelectModel> implements OnClickListener {
        private Context mContext;
        private List<DataType> data;
        private LayoutInflater layoutInflater;
        private IHomeTabLayout rootView;
        private OnTabSelectedListener listener;
        private int mLayoutId;
        private int currSelectPosition;

        public AbsTabAdapter(Context context, @LayoutRes int layoutId) {
            mContext = context;
            layoutInflater = LayoutInflater.from(mContext);
            mLayoutId = layoutId;
        }

        private void registerRootView(IHomeTabLayout rootView) {
            this.rootView = rootView;
        }

        public void setData(List<DataType> data) {
            this.data = data;
        }

        public List<DataType> getData() {
            return data;
        }

        public int getCount() {
            return data == null ? 0 : data.size();
        }

        public DataType getItem(int position) {
            if (data == null || data.size() < position) {
                return null;
            }
            return data.get(position);
        }

        public View getItemView(int position) {
            View root = layoutInflater.inflate(mLayoutId, null);
            root.setTag(position);
            root.setOnClickListener(this);
            return getView(getItem(position), root);
        }

        public void notifyDataSetChange(int position) {
            View childByIndex = rootView.getChildByIndex(position);
            if (childByIndex == null) {
                return;
            }
            getView(getItem(position), childByIndex);
        }

        public void notifyDataSetChange() {
            rootView.refresh();
        }

        public abstract View getView(DataType model, View root);

        @Override
        public void onClick(View v) {

            int position = (int) v.getTag();
            selectItem(position, null);
        }

        private void selectItem(int position, Bundle bundle) {

            if(getOnTabSelectedListener()!=null&&getOnTabSelectedListener().onBeforeSelect(position)){
                return ;
            }
            if (getItem(position).isSelected()) {
                if (getOnTabSelectedListener() != null) {
                    getOnTabSelectedListener().onSelectedAgain(position, bundle);
                }
                return;
            }

            boolean canSelect = getItem(position).getFragmentClass() != null;
            if (canSelect) {
                for (int i = 0; i < getCount(); i++) {
                    getItem(i).setSelected(false);
                }

                getItem(position).setSelected(true);
                for (int i = 0; i < getCount(); i++) {
                    notifyDataSetChange(i);
                }
            }
            if (getOnTabSelectedListener() != null) {
                getOnTabSelectedListener().onSelected(position, bundle);
            }
            currSelectPosition = position;
        }

        public void setOnTabSelectedListener(OnTabSelectedListener l) {
            listener = l;
        }

        public OnTabSelectedListener getOnTabSelectedListener() {
            return listener;
        }

    }

    public void setAdapter(AbsTabAdapter adapter) {
        mAdapter = adapter;
        mAdapter.registerRootView(this);
        refresh();
    }

    public void setCurrent(int position, Bundle bundle) {
        if (mAdapter == null || position >= mAdapter.getCount()) {
            return;
        }

        mAdapter.selectItem(position, bundle);
    }

    public AbsTabAdapter getAdapter() {
        return mAdapter;
    }

    @Override
    public void refresh() {
        if (mAdapter == null) {
            return;
        }
        removeAllViews();
        for (int i = 0; i < mAdapter.getCount(); i++) {
            View itemView = mAdapter.getItemView(i);
            LayoutParams lp = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1);
            addView(itemView, lp);
        }
    }

    @Override
    public View getChildByIndex(int index) {
        if (getChildCount() <= index) {
            return null;
        }
        return getChildAt(index);
    }

    @Override
    public int getItemCount() {
        return mAdapter.getCount();
    }

    @Override
    public void setOnTabSelectedListener(OnTabSelectedListener lis) {
        mAdapter.setOnTabSelectedListener(lis);
    }

    @Override
    public OnTabSelectedListener getOnTabSelectedListener() {
        return mAdapter.getOnTabSelectedListener();
    }

    @Override
    public Class<HomeTabFragment> getTabFragmentClass(int position) {
        return mAdapter.getItem(position).getFragmentClass();
    }

    public interface OnTabSelectedListener {
        boolean onBeforeSelect(int position);
        void onSelected(int position, Bundle bundle);
        void onSelectedAgain(int position, Bundle bundle);
    }

    @Override
    protected Parcelable onSaveInstanceState() {
        Parcelable parcelable = super.onSaveInstanceState();
//        return parcelable;
        SavedState state = new SavedState(parcelable);
        if (mAdapter != null) {
            state.position = mAdapter.currSelectPosition;
        }
        return state;
    }

    @Override
    protected void onRestoreInstanceState(Parcelable state) {
        if (!(state instanceof SavedState)) {
            super.onRestoreInstanceState(state);
            return;
        }
        SavedState state1 = (SavedState) state;
        if (mAdapter != null) {
            mAdapter.selectItem(state1.position, null);
        }
        super.onRestoreInstanceState(((SavedState) state).getSuperState());
    }

    static class SavedState extends BaseSavedState {
        int position;

        SavedState(Parcelable superState) {
            super(superState);
        }

        private SavedState(Parcel in) {
            super(in);
            this.position = in.readInt();
        }

        @Override
        public void writeToParcel(Parcel out, int flags) {
            super.writeToParcel(out, flags);
            out.writeInt(this.position);
        }

        public static final Creator<SavedState> CREATOR =
                new Creator<SavedState>() {
                    public SavedState createFromParcel(Parcel in) {
                        return new SavedState(in);
                    }

                    public SavedState[] newArray(int size) {
                        return new SavedState[size];
                    }
                };
    }
}
